Imports System.Windows.Forms
Imports System.Xml
Imports System.Data.SqlClient

Public Class FormConnectToServer
    Public Servers As List(Of ServerLoginItem)
    Public Successful As Boolean = False
    Public Function getCS() As String
        Dim CS As String = "Server=" & cboServerName.Text & ";"
        Select Case cboAuthenticationType.Text.ToUpper
            Case "WINDOWS AUTHENTICATION"
                CS = CS & "Integrated Security=SSPI;"
            Case Else
                CS = CS & "user id=" & txtLoginName.Text & ";Password=" & txtPassword.Text & ";"
        End Select
        Return CS
    End Function

    Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click

        OK_Button.Enabled = False
        Dim CS As String = getCS()

        Dim Connection As New SqlConnection(CS)
        Dim ExceptionOccurred As Boolean = False
        Dim EXmessage As String = ""
        Try
            Connection.Open()
        Catch ex As Exception
            MsgBox(ex.Message)
            ExceptionOccurred = True
            EXmessage = ex.Message
        End Try
        Connection.Close()

        If ExceptionOccurred = False Then
            Me.DialogResult = System.Windows.Forms.DialogResult.OK
            Successful = True
            SaveCSIToMemory()
            Me.Close()
        Else
            MsgBox(EXmessage)
        End If
        OK_Button.Enabled = True
    End Sub

    Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click
        'End
        Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
        Me.Close()
    End Sub

    Private Sub FormConnectToServer_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Servers = New List(Of ServerLoginItem)

        If System.IO.File.Exists("Databasesv2.xml") Then
            Dim doc As New XmlDocument
            doc.Load("Databasesv2.xml")
            Dim NodeList As XmlNodeList
            NodeList = doc.SelectNodes("PCG/DatabaseType/SQLServer/Server")
            For Each node As XmlNode In NodeList
                Dim csi As New ServerLoginItem
                For Each a As XmlAttribute In node.Attributes
                    Select Case a.Name
                        Case "Name"
                            csi.Name = a.Value
                            cboServerName.Items.Add(csi.Name)
                        Case "UserName"
                            csi.UserName = a.Value
                        Case "Password"
                            Try
                                csi.Password = Encryption.Decrypt(a.Value)
                            Catch ex As Exception
                            End Try
                        Case "AuthenticationType"
                            csi.AuthenticationType = a.Value
                        Case "RememberPassword"
                            csi.RememberPassword = a.Value
                    End Select
                Next

                Servers.Add(csi)

            Next
        End If

        cboServerType.SelectedIndex = 0
        cboAuthenticationType.SelectedIndex = 0
        If cboServerName.Items.Count > 0 Then
            cboServerName.SelectedIndex = 0
            cboServerName_SelectedIndexChanged(Nothing, Nothing)
        End If
        cboAuthenticationType_SelectedIndexChanged(Nothing, Nothing)
    End Sub

    Private Sub cboAuthenticationType_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboAuthenticationType.SelectedIndexChanged
        If cboAuthenticationType.SelectedIndex = 0 Then
            txtLoginName.Enabled = False
            txtLoginName.Text = ""
            txtPassword.Enabled = False
            txtPassword.Text = ""
            chkRememberPassword.Enabled = False
            chkRememberPassword.Checked = False
        Else
            txtLoginName.Enabled = True
            txtPassword.Enabled = True
            chkRememberPassword.Enabled = True
        End If
    End Sub

    Private Sub cmdTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdTest.Click
        cmdTest.Enabled = False
        OK_Button.Enabled = False
        Cancel_Button.Enabled = False
        Dim CS As String = getCS()

        Dim Connection As New SqlConnection(CS)
        Dim ExceptionOccurred As Boolean = False
        Try
            Connection.Open()
        Catch ex As Exception
            MsgBox(ex.Message)
            ExceptionOccurred = True
        End Try
        Connection.Close()

        If ExceptionOccurred = False Then
            SaveCSIToMemory()
            MsgBox("Connection Successful")
        End If
        cmdTest.Enabled = True
        OK_Button.Enabled = True
        Cancel_Button.Enabled = True
    End Sub

    Private Sub SaveCSIToMemory()
        Dim ExistingItemFound As Boolean = False
        For Each csi As ServerLoginItem In Servers
            If csi.Name.ToUpper = cboServerName.Text.ToUpper Then
                csi.AuthenticationType = cboAuthenticationType.Text
                csi.UserName = txtLoginName.Text
                csi.Password = txtPassword.Text
                csi.RememberPassword = chkRememberPassword.Checked
                ExistingItemFound = True
            End If
        Next
        If ExistingItemFound = False Then
            Dim csi As New ServerLoginItem
            csi.Name = cboServerName.Text
            csi.AuthenticationType = cboAuthenticationType.Text
            csi.UserName = txtLoginName.Text
            csi.Password = txtPassword.Text
            csi.RememberPassword = chkRememberPassword.Checked
            Servers.Add(csi)
        End If

        SaveCSI()
    End Sub

    Private Sub SaveCSI()
        Dim xmlDoc As New XmlDocument
        Dim xmlDeclaration As XmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "")
        xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement)

        Dim RootNode As XmlElement = xmlDoc.CreateElement("PCG")
        RootNode.SetAttribute("Version", "1.0")
        xmlDoc.AppendChild(RootNode)

        Dim DatabaseTypeElement As XmlElement = xmlDoc.CreateElement("DatabaseType")
        RootNode.AppendChild(DatabaseTypeElement)

        Dim SQLServerElement As XmlElement = xmlDoc.CreateElement("SQLServer")
        DatabaseTypeElement.AppendChild(SQLServerElement)

        For Each csi As ServerLoginItem In Servers
            Dim Server As XmlElement = xmlDoc.CreateElement("Server")
            Server.SetAttribute("Name", csi.Name)
            Server.SetAttribute("UserName", csi.UserName)
            If csi.RememberPassword Then
                Server.SetAttribute("Password", Encryption.Encrypt(csi.Password))
            Else
                Server.SetAttribute("Password", "")
            End If
            Server.SetAttribute("AuthenticationType", csi.AuthenticationType)
            Server.SetAttribute("RememberPassword", csi.RememberPassword)
            Dim ProjectSettings As XmlElement = xmlDoc.CreateElement("ProjectSettings")
            Server.AppendChild(ProjectSettings)
            SQLServerElement.AppendChild(Server)

        Next
        xmlDoc.Save("Databasesv2.xml")
    End Sub



    Private Sub cboServerName_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboServerName.SelectedIndexChanged
        For Each csi As ServerLoginItem In Servers
            If csi.Name.ToUpper = cboServerName.Text.ToUpper Then
                cboAuthenticationType.Text = csi.AuthenticationType
                txtLoginName.Text = csi.UserName
                txtPassword.Text = csi.Password
                chkRememberPassword.Checked = csi.RememberPassword
            End If
        Next
    End Sub

    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

    End Sub
End Class
